package br.edu.univas.si.es.correios.model;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.JOptionPane;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;



public class HibernateDAO implements BaseDAO {
	
	private Session session;
    private Transaction transaction;
    private Query query;
    
	public void create(Order order){
		try{
            this.session = HibernateUtil.getSessionFactory().openSession();
            transaction = session.beginTransaction();
            session.saveOrUpdate(order);
            transaction.commit();
            session.close();
        } catch (HibernateException e) { 
            JOptionPane.showMessageDialog(null, "Erro ao persistir os dados.\n"+e.getMessage(), null, JOptionPane.ERROR_MESSAGE);
            e.printStackTrace(); 
        }
	}
	
	public void delete(Order order){
		try{
			this.session = HibernateUtil.getSessionFactory().openSession();
			transaction = session.beginTransaction();
			session.delete(order);
			transaction.commit();
			session.close();
		} catch (HibernateException e) { 
			JOptionPane.showMessageDialog(null, "Erro ao deletar registro.\n"+e.getMessage(), null, JOptionPane.ERROR_MESSAGE);
			e.printStackTrace(); 
		}
	}
	 
	public Integer getOrderID(Order order){
	
		try{
			
			this.session = HibernateUtil.getSessionFactory().openSession();
			this.query = session.createSQLQuery("SELECT last_value FROM pedidos_num_rastreamento_seq"); 
			int id = (Integer) query.list().get(0); 
			session.close();
			return id;
			
		}catch(Exception e){
			System.out.println("Erro: " + e.getMessage());
			e.printStackTrace();
			return 0;
		}
	}
	
	public Order retrieveOne(int orderNumber){
		Order order = new Order();
		try{
			 this.session = HibernateUtil.getSessionFactory().openSession();
	         transaction = session.beginTransaction();
	         order = (Order) session.get(Order.class, orderNumber);
	         session.close();
		} catch (HibernateException e) { 
			JOptionPane.showMessageDialog(null, "Erro ao Retornar registro.\n"+e.getMessage(), null, JOptionPane.ERROR_MESSAGE);
			e.printStackTrace(); 
		}
		return order;
	}
	
	public void update(Order order, String field, String newData){
		create(order);
	}
	
	public boolean checkOrderNumber(int orderNumber) {
		try {			
			 this.session = HibernateUtil.getSessionFactory().openSession();
	         transaction = session.beginTransaction();
	         Order order = (Order) session.get(Order.class, orderNumber);
	         session.close();
	         
			orderNumber = (order.getOrderNumber());
							
		} catch (HibernateException e) { 
			e.printStackTrace(); 
			return false;
		}
		return true;
	}
	
}
